﻿using System.Collections.Generic;
using Microsoft.SharePoint;
using SharePoint.Orm.Helpers;

namespace SharePoint.Orm.SiteBuilders {
	/// <summary>
	/// Provides the ability to find/add views.
	/// </summary>
	public class ViewBuilder : BuilderBase<SPView> {
		/// <summary>
		/// Required.  The list to add the view to.
		/// </summary>
		public SPList List { get; set; }

		/// <summary>
		/// Required.  A list of the *internal* names of fields to display in the view.  If this is a document library 
		/// consider: "DocIcon", "LinkFilename", [your fields], "Modified", "Editor".
		/// </summary>
		public IEnumerable<string> ViewFields { get; set; }

		/// <summary>
		/// Optional, default = true.
		/// </summary>
		public bool Paged { get; set; }

		/// <summary>
		/// Optional, default = 100.  The number of results per page.
		/// </summary>
		public uint RowLimit { get; set; }

		/// <summary>
		/// Optional.  A CAML query such as '<OrderBy><FieldRef Name='Modified' Ascending='FALSE' /></OrderBy>'.  Remember to 
		/// use internal names for fields.
		/// </summary>
		public string Query { get; set; }

		/// <summary>
		/// Optional, default = false.  
		/// </summary>
		public bool MakeViewDefault { get; set; }

		/// <summary>
		/// The name of the view.  The default view for most lists is "All Items".  The default view for document libraries is "All Documents".
		/// </summary>
		public string ViewName { get; set; }

		/// <summary>
		/// Optional, default = false.
		/// </summary>
		public bool Hidden { get; set; }

		/// <summary>
		/// Optional, default = SPViewCollection.SPViewType.Html.
		/// </summary>
		public SPViewCollection.SPViewType ViewType { get; set; }

		/// <summary>
		/// Optional, default = false.
		/// </summary>
		public bool PersonalView { get; set; }

		/// <summary>
		/// Initializes default properties of the view (see individual property descriptions).
		/// </summary>
		public ViewBuilder() {
			Paged = true;
			RowLimit = 100;
			Query = null;
			MakeViewDefault = false;
			Hidden = false;
			ViewType = SPViewCollection.SPViewType.Html;
			PersonalView = false;
		}

		/// <summary>
		/// Finds or adds a view.
		/// </summary>
		/// <returns></returns>
		public override SPView FindAdd() {
			if (List == null) throw new SPOrmException("List is required.");
			if (ViewName == null) throw new SPOrmException("ViewName is required.");
			if (ViewFields == null) throw new SPOrmException("ViewFields is required.");

			SPView view = SPListHelper.FindOrAddView(List, ViewName, ViewFields, Query, RowLimit, Paged, MakeViewDefault, ViewType, PersonalView);

			if (Hidden) {
				view.Hidden = true;
				view.Update();
			}

			return view;
		}
	}
}
